package com.bidevalution.business.integrate;

import java.util.Map;
import java.util.Map.Entry;
import org.springframework.util.StringUtils;

import com.bidevalution.business.factory.StepJobFactory;
import com.bidevalution.business.factory.StepJobJdbcFactory;
import com.bidevalution.business.function.FunctionCalculator;
import com.bidevalution.business.service.JdbcTemplateService;
import com.bidevalution.dao.entity.BeSectionStepJob;
import com.bidevalution.support.util.MapUtil;
import com.bidevalution.support.util.OConvertUtil;
import com.google.common.collect.Maps;

/**
 * 标段参数计算公式解析
 * 
 * @author daizhifeng
 * @date 2019年11月25日 上午11:43:52
 * @version V2.0
 */
public class ParameterFormulaExecuteJob implements StepJobFactory {
	private JdbcTemplateService jdbcTemplateService;

	@Override
	public Boolean execute(BeSectionStepJob beSectionStepJob, String submitCode,String expertId, String layoutCode,
			Map<String, Object> paramMap) throws Exception {
		String formulaConfig = beSectionStepJob.getJobContent();
		if (!StringUtils.isEmpty(formulaConfig)) {
			formulaConfig = formulaConfig.trim();
			if(paramMap == null) {
				paramMap = Maps.newHashMap();
			}
			paramMap.put("$sectionStepId", beSectionStepJob.getSectionStepId());
			paramMap.put("$submitCode", submitCode);
			paramMap.put("$sectionId", beSectionStepJob.getSectionId());
			paramMap.put("$layoutCode", beSectionStepJob.getLayoutCode());
			if (formulaConfig.toLowerCase().startsWith("{mel[")) {
				// 内置自定义对象,对象转换
				paramMap.put("OConvertUtil", new OConvertUtil());
				formulaConfig = formulaConfig.substring(5, formulaConfig.length() - 2);
				FunctionCalculator.computeMVEL(formulaConfig, paramMap);
			} else if (formulaConfig.toLowerCase().startsWith("{ael[")){
				formulaConfig = formulaConfig.substring(5, formulaConfig.length() - 2);
				FunctionCalculator.computeAviator(formulaConfig, paramMap);
			}
			// 遍历参数并保存
			for (Entry<String, Object> entry : paramMap.entrySet()) {
				// 排除不应该保存的key值
				if (entry.getKey().equals("OConvertUtil") || entry.getKey().toUpperCase().startsWith("$PARAM_")) {
					continue;
				}
				// 删除已存在结果
				jdbcTemplateService.update(
						" DELETE FROM be_section_parameter WHERE section_id=:sectionId and param_id=:paramId ",
						MapUtil.create().putValue("sectionId", beSectionStepJob.getSectionId())
								.putValue("paramId", entry.getKey()).getMap());
				// 数据插入
				jdbcTemplateService.update(
						"insert into be_section_parameter(section_id,param_id,param_type,param_value,create_time,update_time) values(:sectionId,:paramId,2,:paramValue,now(),now())",
						MapUtil.create().putValue("sectionId", beSectionStepJob.getSectionId())
								.putValue("paramId", entry.getKey()).putValue("paramValue", entry.getValue()).getMap());

			}
			return true;
		}
		return false;
	}

	@Override
	public void setJdbcTemplateService(JdbcTemplateService jdbcTemplateService) {
		this.jdbcTemplateService = jdbcTemplateService;
	}

}
